import axios from 'axios'

import { ElMessage } from 'element-plus'

const http = axios.create({
    baseURL: 'http://localhost:8000'
})
http.interceptors.request.use(function (request) {
    const token = localStorage.getItem('token')
    if (token) {
        request.headers.Authorization = `Bearer ${token}`
    }
    return request
})
http.interceptors.response.use(function (response) {
    return response
}, function (error) {
    if (error.status == 400) {
        // 关闭页面中所有的消息提示框
        ElMessage.closeAll()
        ElMessage.warning('出错了, 请稍后重试')
        return false
    }
    if (error.status == 403) {
        // 关闭页面中所有的消息提示框
        ElMessage.closeAll()
        ElMessage.warning(error.response.data.detail)
        // 移除过期的token
        localStorage.removeItem('token')
        location.href = "#/login"
        return false
    }
    // return Promise.reject()会将错误向后继续传递
    return Promise.reject(error)
    // return false可以阻止显示报错信息
})

export default http